package com.zyk.problem;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangsan
 * @date 2021/5/16 11:08
 */
public class LongestLengthInSumArrayHas1AndMinus1Same {

    public static int longestLengthOfSubArraySumEqualK(int[] nums, int K) {
        if (nums == null || nums.length == 0)
            return 0;
        Map<Integer, Integer> map = new HashMap<>();    // 前缀和为key的数, 最早出现的位置value
        map.put(0, -1);
        int sum = 0, N = nums.length;
        int ans = -1;
        for (int i = 0; i < N; i++) {
            sum += nums[i];
            int key = sum - K;
            if (map.containsKey(key)) {     // 之前有前缀和为这个的位置, 统计答案
                ans = Math.max(ans, (i - map.get(key)));
            }
            if (!map.containsKey(sum)) {    // 走的时候别忘记把自己放进去
                map.put(sum, i);
            }
        }
        return ans;
    }

    public static int longestLen(int[] nums) {
        int N = nums.length;
        int[] help = new int[N];
        for (int i = 0; i < nums.length; i++) {
            help[i] = Math.abs(nums[i]) == 1 ? nums[i] : 0;
        }
        return longestLengthOfSubArraySumEqualK(help, 0);
    }


    public static void main(String[] args) {
        int maxLen = 10;
        int[] nums = generateArr(maxLen);
        System.out.println(longestLen(nums));
        System.out.println(Arrays.toString(nums));
    }

    public static int[] generateArr(int maxLen) {
        maxLen = (int) (Math.random() * maxLen);
        int[] res = new int[maxLen];
        for (int i = 0; i < res.length; i++) {
            res[i] = Math.random() < 0.7 ? (Math.random() < 0.5 ? 1 : -1) : (int) (Math.random() * 200);
        }
        return res;
    }

}
